import React, {Component} from 'react';
import {Button} from 'antd';
import axios from 'axios';
import config from 'src/commons/config-hoc';
import { PageContent } from 'ra-lib';
import Map from 'ol/Map';
import View from 'ol/View';
import LayerVector from 'ol/layer/Vector';
import SourceVector from 'ol/source/Vector';
import { defaults } from 'ol/control';
import 'ol/ol.css';
import { Fill, Stroke, Style, Icon, Circle as CircleStyle } from 'ol/style';
import {Image,Tile as TileLayer, Vector as VectorLayer,Heatmap} from 'ol/layer';
import { fromLonLat, transform ,transformExtent,toLonLat} from 'ol/proj';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import styles from './styles.less';
import { OSM } from 'ol/source';
import { LineString, Polygon } from 'ol/geom';
import { getArea, getLength,getDistance } from 'ol/sphere';
import XYZ from 'ol/source/XYZ';
import { Modify } from 'ol/interaction';

const defaultCenterLocation = [114.16546,22.27534];
const defaultZoom = 13;

@config({
    title: '地图',
    side: false,
    path: '/kmb-map',
})
export default class index extends Component {
    state = {
        mapCenter: defaultCenterLocation,
        zoom: defaultZoom,
        dataSource:[]
    };
    componentDidMount() {
        setTimeout(()=>{
            this.mapInitLoad();
        },300)
    }

    mapInitLoad=()=>{
        const { mapCenter,zoom } = this.state;
        //m：路线图
        //t：地形图
        // ​p：带标签的地形图
        // ​s：卫星图
        //y：带标签的卫星图
        // ​h：标签层（路名、地名等）
        this.map_layer = new TileLayer({
            visible: true,
            source: new XYZ({
                url: 'http://www.google.cn/maps/vt?lyrs=r@189&gl=cn&x={x}&y={y}&z={z}'
            })
        });
        this.raster = new TileLayer({
            source: new OSM(),
        });

        this.pointSourceVector = new SourceVector();
        this.point_layer = new LayerVector({
            source: this.pointSourceVector,
            overlaps: false,
            wrapX: false,
            zIndex:10,
        })
        this.pointPathSourceVector = new SourceVector();
        this.point_layer_path = new LayerVector({
            source: this.pointPathSourceVector,
            overlaps: false,
            wrapX: false,
            zIndex:10,
        })

        this.map_view = new View({
            projection: 'EPSG:4326',
            center: mapCenter,
            zoom: zoom,
            // minZoom:4
        })

        //画图
        // this.sourceDraw = new VectorSource({wrapX: false});
        // this.vectorDraw = new VectorLayer({
        //     source: this.sourceDraw,
        // });
//画图
//         this.sourceDrawPlot = new VectorSource({wrapX: false});


        //7、创建地图组件
        this.map = new Map({
            view: this.map_view,
            layers: [
                this.raster,
                this.map_layer,
                this.point_layer,
                this.point_layer_path,
            ],
            // overlays: [this.overlay],
            controls: defaults({
                // attributionOptions: ({
                //     collapsible: false
                // }),
                // //清除地图上默认样式（放大、缩小、旋转按钮等）
                attribution: false,
                // rotate: false,
                // zoom: false
            }),
            target: this.mapDom
        });


        var modify = new Modify({
            hitDetection: this.point_layer_path,
            source: this.pointPathSourceVector,
        });
        modify.on(['modifystart', 'modifyend'], (evt)=> {
            this.mapDom.style.cursor = evt.type === 'modifystart' ? 'grabbing' : 'pointer';
            console.log(evt,"modifystart', 'modifyend");
            let features = evt.features;
            let feature = features.array_[0];
            let feature2 = features.array_[1];
            let geometry=feature.getGeometry();
            // let geometry2=feature2.getGeometry();
            let coordinate=geometry.getCoordinates();
            // let coordinate2=geometry2.getCoordinates();

            console.log(coordinate,"features");
            this.setState({path:coordinate})
        });
        let overlaySource = modify.getOverlay().getSource();
        overlaySource.on(['addfeature', 'removefeature'], (evt)=> {
            this.mapDom.style.cursor = evt.type === 'addfeature' ? 'pointer' : '';
            // console.log(evt,"addfeature', 'removefeature");
        });
        // this.drawFrame.on('drawend',  (e)=> {
        //     this.drawing = false;
        //     this.previewLine.getGeometry().setCoordinates([]);
        //     // tracingFeature = null;
        //     let feature=e.feature;
        //     let geometry=feature.getGeometry();
        //     let coordinate=geometry.getCoordinates();
        //
        // });
        this.map.addInteraction(modify);

        this.map.on("click",  (e)=> {
            //要素选中事件，获取选中要素信息
            // let coordinate = e.coordinate;
            // this.addVectorPoint( transform(coordinate, 'EPSG:3857' ,'EPSG:4326'), {}, '','',true)
            this.map.forEachFeatureAtPixel(e.pixel,  (feature)=> {
                console.log(feature.values_,"feature");
                let values = feature.values_;
                if(!values.data) return false;
                return feature;
            });

        });
        this.map.on("moveend",(e)=>{
            let zoom = this.map.getView().getZoom();
            console.log(zoom,"zoom");
        });
        if(this.props.location.state&&this.props.location.state.data){
            let data = this.props.location.state.data;
            let list = [];
            data&&data.children&&data.children.forEach(item=>{
                let location = item.location.split(',');
                let location3857 = transform(location,'EPSG:4326', 'EPSG:3857' );
                location = transform(location3857, 'EPSG:3857','EPSG:4326' )
                this.addVectorPoint(location)
                list.push(location)
            })
            if(list.length<1) return false;
            if(!data.path){
                let pathArr =[];
                list.forEach((item,index)=>{
                    pathArr.push(item.reverse().join(','))
                })
                let url = 'https://roads.googleapis.com/v1/snapToRoads';
                axios.get(url, {
                    params: {
                        path: pathArr.join('|'),
                        key:'AIzaSyCrpg574REcNAAVOix_mKrq6Lo2OOzu2vc',
                        interpolate:true
                    }
                }).then((response)=> {
                    console.log(response.data.snappedPoints);
                    let snappedPoints= response.data.snappedPoints;
                    let arr = [];
                    snappedPoints.forEach(item=>{
                        let location = item.location;
                        arr.push([location.longitude,location.latitude])
                        this.loadLineFeature(arr)

                    })
                })
            }else {
                this.loadLineFeature(data.path)

            }
        }
    }
    handleSubmit = (values) => {
        let data = this.props.location.state.data;
        const {path} = this.state;
        data.path = path;
        let ajaxMethod = this.props.ajax.put;
        let ajaxApi = '/api/update';
        let successTip = '修改成功！' ;


        ajaxMethod(ajaxApi, data, { successTip })
            .then(() => {
                this.props.history.push('/kmb-manage')
            })
    };
    addVectorPoint =( location, info, datatype,icon,checkbox)=> {
        //添加矢量要素点
        this.newFeature = new Feature({
            data: info,
            geometry: new Point(location),
            datatype
        });
        let url = icon?icon:require('./image/bus.png');
        //图标样式
        let iconStyle = new Style({
            image: new Icon(
                /** @type {olx.style.IconOptions} */ ({
                    anchor: [0.5, 40],
                    anchorXUnits: "fraction",
                    anchorYUnits: "pixels",
                    src: url,
                    // size:[115,233],
                    // scale: datatype==='weather'?0.1:1
                })
            ),

        });

        this.newFeature.setStyle(iconStyle);

        //清除矢量图层里的所有要素
        // layer.getSource().clear();

        //将当前要素添加到矢量数据源中
        this.point_layer.getSource().addFeature(this.newFeature);
        this.point_layer.setVisible(true);

    }

    /**
     * 加载线
     * @returns {boolean}
     */
    loadLineFeature = (location)=>{
        // if(this.atmosphereLayer){
        //     this.map.removeLayer(this.atmosphereLayer);
        //     this.atmosphereLayer = null;
        //     return false;
        // }
        this.lineFeature = new Feature(
            new LineString(location)
        );
        let iconStyle = new Style({
            stroke: new Stroke({
                width: 5,
                color: '#0D21A1',
            }),
        });

        this.lineFeature.setStyle(iconStyle);
        this.point_layer_path.getSource().addFeature(this.lineFeature);
    }

    render() {
        return (
            <PageContent style={{position:'relative'}}>
                <div className={styles.buttonWrap}>
                    <Button onClick={()=>this.props.history.push('/kmb-manage')}>返回</Button>
                    <Button type="primary" onClick={()=>this.handleSubmit()}>確認</Button>
                </div>
                <div ref={ref =>this.mapDom = ref} className={styles.olmap}></div>
            </PageContent>
        );
    }
}
